import { ref,Ref } from 'vue'
import {awaitFn} from '@dashboard/utils'
import {getURLParameters} from '@dashboard/api'
import {componentData,menuCompData,compCategoryType} from '@drag/componentData'
type selected = string|boolean;
declare global {
    interface Window {
        data: Ref<componentData[]>;
        draggable:Ref<boolean>;
        compCategory:Ref<compCategoryType[]>
    }
}
/**当前选中的组件高亮 */
export const select = ref<selected>(false);

/**页面拖拽好的数据 */
export const data = ref<componentData[]>([]);
window.data = data;

/**页面初始数据 */
export let initData:componentData[] = [];

/**渲染组件是否可拖拽 */
export const draggable = ref(false);

/**组件类别 */
export const compCategory = ref<compCategoryType[]>([])

/**骨架屏状态【组件类别没回来时】 */
export const loading = ref(true)

/**父窗口window */
export let parentWindow:MessageEventSource | null = null;

/**设备类型 */
export const device = ref<'pc' | 'mobile'>('pc');

/**页面标识【业务主键】 */
export let pageGuid:string = ''

export const origin = ref();
export const AccessToken = ref()
export const cookie = ref()

/**
 * 初始化仓库数据
 */
export function useStore(){
    device.value = getURLParameters('device')||'pc';
    // 获取当前页面渲染数据
    window.addEventListener('message', function(event) {
        if (event.data && event.data.type === 'DashBoard') {
            parentWindow = event.source;
            let postMessageData = Array.isArray(event.data.data) ? event.data.data : [];
            initData = JSON.parse(JSON.stringify(postMessageData))
            data.value.push(...JSON.parse(JSON.stringify(postMessageData)));// 数据
            device.value = event.data.device;// 设备类型
            pageGuid = event.data.guid;// 页面标识
            origin.value = event.data.origin;
            AccessToken.value = event.data.AccessToken;
            cookie.value = event.data.cookie;
        }
    }, false);
    /*if(import.meta.env.DEV){
        setTimeout(()=>{
            // let api = [
            //     {"tb":"Fee_Reimbursement","tag":"sel","pages":1,"tol":30,"Title":"费用报销","field":"Fee_ReimbursementOID,Code,Date_Reim,Total,FinanceMonth,ReimType,ReimObject,AccountInfo,Remark","FieldName_CN":"主键,单据编号,报销日期,合计金额,财务月份,费用类别,报销对象,收款账号信息,备注","fieldType":"","guid":1730189450790,"alias":1730189450790},
            //     {"tb":"Fee_ReimbursementMX","tag":"sel","pages":1,"tol":30,"Title":"报销明细","Relation":"1","ParentOID":1730189450790,"R_MainField":"Fee_ReimbursementOID","R_ChildField":"Fee_Reimbursement_FK","field":"Fee_ReimbursementMXOID,BillType,BillDate,CostTotal,Remark,InvoiceSerial,CostName,AccountingItem,ItemName,Remarks,Fee_Reimbursement_FK","FieldName_CN":"主键,票据类型,票据日期,费用金额,摘要,发票号码,成本科目名称,核算项目,事项标题,备注,报销外键","guid":1730191340708,"alias":1730191340708},
            //     {"tb":"Pub_Config","tag":"sel","pages":1,"tol":10,"Title":"参数配置","Relation":"2","field":"Pub_ConfigOID,Config","FieldName_CN":"主键,参数","guid":1731417665651,"alias":1731417665651},
            // ];
            // let config = {
            //     "lvxdj":
            //     // {"fontSize":"","color":"","fontWeight":"","ToType":"StaticData","StaticData":"Orders111","Penetrate":"Disable"},
            //     {"ToType":"DataIndex","FieldSelect":[1730189450790,"Date_Reim"],"DataIndex":0,"fontSize":"30px"},
            //     "ykcfa":{"FieldSelect":[1730189450790,"Date_Reim"],"ToType":"CustomTo","CustomTo":"function main(field,data){\r\n    return data.find(e=>e[field]=='2005-09-10 20:12:45')[field];\r\n}"}
            // };
            // let config = {"lvxdj":{"ToType":"DataIndex","FieldSelect":[1730189450790,"Date_Reim"],"DataIndex":0,"fontSize":"30px"},"ykcfa":{"FieldSelect":[1730189450790,"Date_Reim"],"ToType":"DataIndex","Penetrate":"Disable","DataIndex":1}}
            // let demoDatas:any = {api,config,"name":"7d8651dc-8248-44b3-9e68-f1f3d4cc5c25","title":"悬浮卡片-绑定","tabs":true,"guid":1730441099970,"data":[{"h6":"Orders","h3":"1,587","span1":"+11%","span2":"From previous period"},{"h6":"Revenue","h3":"$46,782","span1":" -29%","span2":"From previous period"},{"h6":"Average Price","h3":"$15.9","span1":" 0%","span2":"From previous period"},{"h6":"Product Sold","h3":"1,890","span1":" +89%","span2":"Last year"}],"defaultData":[{"h6":"Orders","h3":"1,587","span1":"+11%","span2":"From previous period"},{"h6":"Revenue","h3":"$46,782","span1":" -29%","span2":"From previous period"},{"h6":"Average Price","h3":"$15.9","span1":" 0%","span2":"From previous period"},{"h6":"Product Sold","h3":"1,890","span1":" +89%","span2":"Last year"}]};
            // let demoData:any = {"title":"查询组件","name":"query","tabs":false,"guid":1734444947217,"config":{}};
            // let table:any = {api,"title":"表格","name":"table","tabs":true,"guid":1734615549506,"config":{}};
            //data.value.push(table);
            // data.value.push(demoData)
            // data.value.push(demoDatas)
        },1000)
    }*/
    // 获取组件类别与组件
    awaitFn<any>(resolve=>(window as any).api&&resolve((window as any).api),'获取api失败',20000).then(async res=>{
        //组件类别
        (await res.compCategory).forEach((e)=>compCategory.value.push({...e,children:[]}))
        compCategory.value.sort((a,b)=>a.sort-b.sort)
        loading.value = false;
        (window as any).component = [];
        // 组件
        res.component.forEach(async item => {
            let data = await item.data;
            try {
                (window as any).component.push({name:data.name,files:{...JSON.parse(data.code)}})
            } catch (e) {}
            let parent = compCategory.value.find(o=>o.name===data.parentOID);
            if(!item)return console.log('未找到分类',data);
            parent?.children.push(toCompData(data))
            parent?.children.sort((a,b)=>a.sort-b.sort)
        });
    })
    /**
     * 处理组件数据【添加、删除、修改 组件属性】
     * @param data 组件初始数据 
     */
    function toCompData(data:menuCompData){
        let newData:menuCompData = JSON.parse(JSON.stringify(data));
        // 默认有标签页
        if(!('tabs' in newData))newData.tabs = true;
        return newData
    }
}